import React, { useState, useRef, useEffect } from 'react';
import { useEditorStore, useProjectStore } from '../../stores';
import { useMessage } from '../../hooks/useMessage';
import { FaCircleXmark, FaCopy, FaDownload, FaFile, FaFolder, FaPython, FaEllipsisVertical, FaPenToSquare, FaTrash, FaUpRightFromSquare } from 'react-icons/fa6';
import styles from './ExportDialog.module.css';

const ExportDialog = ({ 
  isOpen, 
  onClose
}) => {

  const { getCurrentCode } = useEditorStore();
  const { getAllFiles, getProjectName } = useProjectStore();
  const { success, error, clearMessages } = useMessage();
  const [copyStatus, setCopyStatus] = useState('');
  const [code, setCode] = useState('');
  const [fileName, setFileName] = useState('main.py');
  const [projectFiles, setProjectFiles] = useState([]);
  const [totalSize, setTotalSize] = useState(0);
  const [contextMenu, setContextMenu] = useState({
    isVisible: false,
    position: { x: 0, y: 0 },
    targetFile: null
  });
  const [renameDialog, setRenameDialog] = useState({
    isOpen: false,
    file: null,
    newName: ''
  });
  const [deleteConfirm, setDeleteConfirm] = useState({
    isOpen: false,
    file: null
  });
  const textareaRef = useRef(null);
  const dialogRef = useRef(null);

  // 检测移动端设备
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取文件图标
  const getFileIcon = (fileName) => {
    const extension = fileName.split('.').pop()?.toLowerCase();
    switch (extension) {
      case 'py':
        return <FaPython className={styles.fileIcon} />;
      default:
        return <FaFile className={styles.fileIcon} />;
    }
  };

  // 构建文件树结构
  const buildFileTree = (files) => {
    const tree = {};
    
    files.forEach(file => {
      const pathParts = file.name.split('/');
      let current = tree;
      
      pathParts.forEach((part, index) => {
        if (index === pathParts.length - 1) {
          // 这是文件
          current[part] = { ...file, isFile: true };
        } else {
          // 这是文件夹
          if (!current[part]) {
            current[part] = { isFile: false, children: {} };
          }
          current = current[part].children;
        }
      });
    });
    
    return tree;
  };

  // 渲染文件树节点
  const renderFileTreeNode = (node, path = '', level = 0) => {
    const items = [];
    
    Object.entries(node).forEach(([name, item]) => {
      const currentPath = path ? `${path}/${name}` : name;
      
      if (item.isFile) {
        // 渲染文件
        items.push(
          <div key={item.id} className={styles.fileListItem} style={{ paddingLeft: `${16 + level * 20}px` }}>
            {/* 层级指示器 */}
            {level > 0 && (
              <div className={styles.levelIndicator} style={{ width: `${level * 20}px` }}>
                {Array.from({ length: level }, (_, i) => (
                  <span key={i} className={styles.levelLine}></span>
                ))}
              </div>
            )}
            {getFileIcon(item.name)}
            <span className={styles.fileName}>{name}</span>
            <span className={styles.fileSize}>
              {formatFileSize(item.content ? new Blob([item.content]).size : 0)}
            </span>
            <div className={styles.fileActions}>
              <button
                className={styles.actionButton}
                onClick={(e) => handleFileAction(e, item)}
                title="文件操作"
              >
                <FaEllipsisVertical />
              </button>
            </div>
          </div>
        );
      } else {
        // 渲染文件夹
        items.push(
          <div key={currentPath} className={styles.folderItem} style={{ paddingLeft: `${16 + level * 20}px` }}>
            {/* 层级指示器 */}
            {level > 0 && (
              <div className={styles.levelIndicator} style={{ width: `${level * 20}px` }}>
                {Array.from({ length: level }, (_, i) => (
                  <span key={i} className={styles.levelLine}></span>
                ))}
              </div>
            )}
            <FaFolder className={styles.folderIcon} />
            <span className={styles.folderName}>{name}</span>
          </div>
        );
        
        // 递归渲染子项
        if (item.children) {
          items.push(...renderFileTreeNode(item.children, currentPath, level + 1));
        }
      }
    });
    
    return items;
  };

  // 文件操作处理函数
  const handleFileAction = (event, file) => {
    event.preventDefault();
    event.stopPropagation();
    
    setContextMenu({
      isVisible: true,
      position: { x: event.clientX, y: event.clientY },
      targetFile: file
    });
  };

  const handleCloseContextMenu = () => {
    setContextMenu({ isVisible: false, position: { x: 0, y: 0 }, targetFile: null });
  };

  const handleRenameFile = (file) => {
    setRenameDialog({
      isOpen: true,
      file: file,
      newName: file.name
    });
    handleCloseContextMenu();
  };

  const handleDeleteFile = (file) => {
    setDeleteConfirm({
      isOpen: true,
      file: file
    });
    handleCloseContextMenu();
  };

  const handleOpenFile = (file) => {
    // 这里可以添加打开文件的逻辑
    success(`打开文件: ${file.name}`);
    handleCloseContextMenu();
  };

  const handleExportFile = (file) => {
    // 导出单个文件
    const blob = new Blob([file.content || ''], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = file.name;
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
    success(`文件 ${file.name} 导出成功！`);
    handleCloseContextMenu();
  };

  const handleConfirmRename = async () => {
    if (renameDialog.newName.trim() && renameDialog.file) {
      // 这里可以添加重命名文件的逻辑
      success(`文件重命名为: ${renameDialog.newName}`);
      setRenameDialog({ isOpen: false, file: null, newName: '' });
    }
  };

  const handleConfirmDelete = async () => {
    if (deleteConfirm.file) {
      // 这里可以添加删除文件的逻辑
      success(`文件 ${deleteConfirm.file.name} 已删除`);
      setDeleteConfirm({ isOpen: false, file: null });
    }
  };

  // 当对话框打开时，获取当前代码并重置状态
  useEffect(() => {
    if (isOpen) {
      // 清空所有状态
      clearMessages();
      setCopyStatus('');
      
      // 获取项目文件列表
      const files = getAllFiles();
      setProjectFiles(files);
      
      // 计算总文件大小
      const totalSizeBytes = files.reduce((total, file) => {
        return total + (file.content ? new Blob([file.content]).size : 0);
      }, 0);
      setTotalSize(totalSizeBytes);
      
      // 直接获取当前编辑器中的代码
      const currentCode = getCurrentCode();
      setCode(currentCode || '// 暂无代码内容');
      setFileName('main.py');
    } else {
      // 对话框关闭时也清空状态
      setCopyStatus('');
    }
  }, [isOpen, getCurrentCode, getAllFiles, clearMessages]);

  useEffect(() => {
    if (isOpen && textareaRef.current) {
      // 自动选中所有文本
      setTimeout(() => {
        textareaRef.current.select();
      }, 100);
    }
  }, [isOpen]);

  // 点击外部关闭 - 移动端优化
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dialogRef.current && !dialogRef.current.contains(event.target)) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleClickOutside);
      document.body.style.overflow = 'hidden';
      // 移动端防止背景滚动
      document.body.style.position = 'fixed';
      document.body.style.width = '100%';
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
      document.body.style.overflow = 'auto';
      document.body.style.position = '';
      document.body.style.width = '';
    };
  }, [isOpen, onClose]);

  // ESC键关闭
  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') {
        if (contextMenu.isVisible) {
          handleCloseContextMenu();
        } else if (renameDialog.isOpen) {
          setRenameDialog({ isOpen: false, file: null, newName: '' });
        } else if (deleteConfirm.isOpen) {
          setDeleteConfirm({ isOpen: false, file: null });
        } else {
          onClose();
        }
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isOpen, onClose, contextMenu.isVisible, renameDialog.isOpen, deleteConfirm.isOpen]);

  // 点击外部关闭上下文菜单
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (contextMenu.isVisible) {
        handleCloseContextMenu();
      }
    };

    if (contextMenu.isVisible) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [contextMenu.isVisible]);

  const handleCopyToClipboard = async () => {
    clearMessages();
    
    try {
      // 尝试现代剪贴板API
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(code);
        setCopyStatus('已复制到剪贴板！');
        success('代码已复制到剪贴板！');
      } else {
        // 回退到选择文本方式
        if (textareaRef.current) {
          textareaRef.current.select();
          textareaRef.current.setSelectionRange(0, 99999); // 移动端兼容
          
          // 尝试执行复制命令
          const successful = document.execCommand('copy');
          if (successful) {
            setCopyStatus('已复制到剪贴板！');
            success('代码已复制到剪贴板！');
          } else {
            setCopyStatus('请手动选择并复制代码');
            error('请手动选择并复制代码');
          }
        }
      }
    } catch (err) {
      console.warn('复制失败:', err);
      setCopyStatus('复制失败，请手动选择并复制');
      error('复制失败，请手动选择并复制');
      // 自动选中文本让用户手动复制
      if (textareaRef.current) {
        textareaRef.current.select();
      }
    }

    // 3秒后清除状态
    setTimeout(() => setCopyStatus(''), 3000);
  };

  const handleSelectAll = () => {
    if (textareaRef.current) {
      textareaRef.current.select();
      textareaRef.current.setSelectionRange(0, 99999);
    }
  };

  // 构建文件的完整路径
  const buildFilePath = (file, allFiles) => {
    if (file.type === 'directory') {
      return null; // 跳过文件夹
    }
    
    const pathParts = [file.name];
    let currentParentId = file.parentId;
    
    // 向上遍历父级目录，构建完整路径
    while (currentParentId && currentParentId !== 'root') {
      const parent = allFiles.find(f => f.id === currentParentId);
      if (parent) {
        pathParts.unshift(parent.name);
        currentParentId = parent.parentId;
      } else {
        break;
      }
    }
    
    return pathParts.join('/');
  };

  const handleDownload = async () => {
    clearMessages();
    
    try {
      // 创建ZIP文件
      const JSZip = (await import('jszip')).default;
      const zip = new JSZip();
      
      // 获取所有文件（包括文件夹）来构建路径
      const allFiles = getAllFiles();
      
      // 添加所有项目文件到ZIP，保持目录结构
      projectFiles.forEach(file => {
        if (file.content) {
          const filePath = buildFilePath(file, allFiles);
          if (filePath) {
            zip.file(filePath, file.content);
          }
        }
      });
      
      // 生成ZIP文件
      const zipBlob = await zip.generateAsync({ type: 'blob' });
      
      // 创建下载链接
      const url = URL.createObjectURL(zipBlob);
      const projectName = getProjectName() || 'Python作品';
      const zipFileName = `${projectName}.zip`;
      
      const link = document.createElement('a');
      link.href = url;
      link.download = zipFileName;
      link.style.display = 'none';
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      URL.revokeObjectURL(url);
      setCopyStatus('作品导出已开始');
      success(`作品 ${zipFileName} 导出成功！`);
      
      // 下载成功后关闭对话框
      setTimeout(() => {
        onClose();
      }, 1000);
    } catch (err) {
      console.warn('导出失败:', err);
      setCopyStatus('导出失败，请重试');
      error('作品导出失败，请重试');
    }
  };

  if (!isOpen) return null;

  return (
    <div className={styles.overlay}>
      <div ref={dialogRef} className={styles.dialog}>
        <div className={styles.header}>
          <h3 className={styles.title}>导出作品</h3>
          <button 
            className={styles.closeButton}
            onClick={onClose}
            title="关闭"
          >
            <FaCircleXmark />
          </button>
        </div>

        <div className={styles.content}>
          <div className={styles.projectTags}>
            <span className={styles.projectTag}>
              {getProjectName() || '未命名作品'}
            </span>
            <span className={styles.fileCountTag}>
              {projectFiles.length} 个文件
            </span>
            <span className={styles.sizeTag}>
              {formatFileSize(totalSize)}
            </span>
          </div>

          <div className={styles.fileList}>
            <div className={styles.fileListHeader}>
              <span>文件列表</span>
            </div>
            <div className={styles.fileListContent}>
              {projectFiles.length > 0 ? (
                renderFileTreeNode(buildFileTree(projectFiles))
              ) : (
                <div className={styles.emptyFileList}>
                  <FaFolder className={styles.emptyIcon} />
                  <span>暂无文件</span>
                </div>
              )}
            </div>
          </div>

          {copyStatus && (
            <div className={styles.statusMessage}>
              {copyStatus}
            </div>
          )}
        </div>

        <div className={styles.actions}>
          <button 
            className={`${styles.actionButton} ${styles.downloadButton}`}
            onClick={handleDownload}
            title="导出作品为ZIP文件"
            disabled={projectFiles.length === 0}
          >
            <FaDownload />
            导出作品
          </button>
        </div>

        <div className={styles.tips}>
          <p className={styles.tipText}>
            💡 提示：导出作品将包含所有项目文件，打包为ZIP格式下载。如果导出失败，请检查浏览器设置或重试。
          </p>
        </div>
      </div>
      
      {/* 文件操作上下文菜单 */}
      {contextMenu.isVisible && (
        <div
          className={styles.contextMenu}
          style={{
            position: 'fixed',
            left: contextMenu.position.x,
            top: contextMenu.position.y,
            zIndex: 10001
          }}
        >
          <div className={styles.contextMenuContent}>
            <button
              className={styles.contextMenuItem}
              onClick={() => handleOpenFile(contextMenu.targetFile)}
            >
              <FaUpRightFromSquare className={styles.contextMenuIcon} />
              打开文件
            </button>
            <button
              className={styles.contextMenuItem}
              onClick={() => handleRenameFile(contextMenu.targetFile)}
            >
              <FaPenToSquare className={styles.contextMenuIcon} />
              重命名
            </button>
            <button
              className={styles.contextMenuItem}
              onClick={() => handleExportFile(contextMenu.targetFile)}
            >
              <FaDownload className={styles.contextMenuIcon} />
              导出文件
            </button>
            <div className={styles.contextMenuDivider} />
            <button
              className={`${styles.contextMenuItem} ${styles.dangerItem}`}
              onClick={() => handleDeleteFile(contextMenu.targetFile)}
            >
              <FaTrash className={styles.contextMenuIcon} />
              删除文件
            </button>
          </div>
        </div>
      )}
      
      {/* 重命名文件弹窗 */}
      {renameDialog.isOpen && (
        <div className={styles.overlay}>
          <div className={styles.smallDialog}>
            <div className={styles.header}>
              <h3 className={styles.title}>重命名文件</h3>
              <button 
                className={styles.closeButton}
                onClick={() => setRenameDialog({ isOpen: false, file: null, newName: '' })}
              >
                <FaCircleXmark />
              </button>
            </div>
            <div className={styles.content}>
              <div className={styles.inputGroup}>
                <label className={styles.inputLabel}>
                  <FaFile className={styles.inputIcon} />
                  新文件名
                </label>
                <input
                  type="text"
                  className={styles.textInput}
                  value={renameDialog.newName}
                  onChange={(e) => setRenameDialog(prev => ({ ...prev, newName: e.target.value }))}
                  placeholder="请输入新文件名"
                  autoFocus
                />
              </div>
            </div>
            <div className={styles.actions}>
              <button 
                className={`${styles.actionButton} ${styles.cancelButton}`}
                onClick={() => setRenameDialog({ isOpen: false, file: null, newName: '' })}
              >
                取消
              </button>
              <button 
                className={`${styles.actionButton} ${styles.confirmButton}`}
                onClick={handleConfirmRename}
                disabled={!renameDialog.newName.trim()}
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 删除确认弹窗 */}
      {deleteConfirm.isOpen && (
        <div className={styles.overlay}>
          <div className={styles.smallDialog}>
            <div className={styles.header}>
              <h3 className={styles.title}>删除文件</h3>
              <button 
                className={styles.closeButton}
                onClick={() => setDeleteConfirm({ isOpen: false, file: null })}
              >
                <FaCircleXmark />
              </button>
            </div>
            <div className={styles.content}>
              <div className={styles.warningMessage}>
                <FaTrash className={styles.warningIcon} />
                <div>
                  <p>确定要删除文件 <strong>{deleteConfirm.file?.name}</strong> 吗？</p>
                  <p className={styles.warningText}>此操作不可撤销，请谨慎操作。</p>
                </div>
              </div>
            </div>
            <div className={styles.actions}>
              <button 
                className={`${styles.actionButton} ${styles.cancelButton}`}
                onClick={() => setDeleteConfirm({ isOpen: false, file: null })}
              >
                取消
              </button>
              <button 
                className={`${styles.actionButton} ${styles.dangerButton}`}
                onClick={handleConfirmDelete}
              >
                删除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ExportDialog;
